package com.air.ota.service.imp;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.air.common.util.QueryCondition;
import com.air.common.util.QueryExpression;
import com.air.ota.mo.CardPwd;
import com.air.ota.mo.CardSequence;
import com.air.ota.mo.InboundMsg;
import com.air.ota.mo.OutboundMsg;
import com.air.ota.mo.RegTrans;
import com.air.ota.service.ICardPwdService;
import com.air.ota.service.ICardSequenceService;
import com.air.ota.service.IOutboundMsgService;
import com.air.ota.service.IPkgSequenceService;
import com.air.ota.service.IRegRequestHandlerService;
import com.air.ota.service.IRegTransService;
import com.air.ota.util.AppConstant;
import com.air.ota.util.HexStringUtil;
import com.air.ota.util.SZTInterface;
import com.air.ota.vo.SZTBaseResponseVO;
import com.air.ota.vo.SZTRegReqTransVO;
import com.air.ota.vo.SZTRegRequestVO;
import com.air.ota.vo.SZTRegResTransVO;
import com.air.ota.vo.UTKRegRequestUplinkVO;
import com.air.ota.vo.UTKRegResponseDownlinkVO;

@Service("regRequestHandlerService")
public class RegRequestHandlerServiceImp implements IRegRequestHandlerService {

	@Autowired
	IRegTransService regTransService;
	@Autowired
	IOutboundMsgService outboundMsgService;
	@Autowired
	ICardSequenceService cardSequenceService;
	@Autowired
	ICardPwdService cardPwdService;
	@Autowired
	IPkgSequenceService pkgSequenceService;
	
	
	@SuppressWarnings("deprecation")
	@Override
	public void process(UTKRegRequestUplinkVO pkgVO, InboundMsg inboundMsg) throws Exception {
		System.out.println("------------Ready to Process Reg Request");
			
		//生成 RegTrans对象，并插入数据库
		SimpleDateFormat sdf  = new SimpleDateFormat("yyyyMMddHHmmss");
		Date effectTime = new Date();
		Date expireTime = new Date();
		expireTime.setYear(effectTime.getYear()+10);
		
		RegTrans trans = new RegTrans();
		trans.setSztId("00000000");
		trans.setCellphone(inboundMsg.getPhoneNumber());
		trans.setTransDate(System.currentTimeMillis());
		trans.setRegSequence(HexStringUtil.bytesToHexString(pkgVO.getRegSequence()));
		trans.setResult(AppConstant._transResult_processing);
		trans.setCardAppSequence(HexStringUtil.bytesToHexString(pkgVO.getCardAppSequence()));
		trans.setCardRandom(HexStringUtil.bytesToHexString(pkgVO.getCardRandom()));
		trans.setLastTransData(HexStringUtil.bytesToHexString(pkgVO.getLastTransData()));
		trans.setCardDeposit(HexStringUtil.bytesToHexString(pkgVO.getCardDeposit()));
		trans.setCardRemain(HexStringUtil.bytesToHexString(pkgVO.getCardRemain()));
		trans.setCardSumDeposit(HexStringUtil.bytesToHexString(pkgVO.getCardSumDeposit()));
		trans.setCardType(HexStringUtil.byteToHexString(pkgVO.getCardType()));
		trans.setCardEffectTime(sdf.format(effectTime));
		trans.setCardExpireTime(sdf.format(expireTime));
		trans.setDeviceTriggerTime(sdf.format(effectTime));
		
		regTransService.insertOrUpdate(trans);
		
		QueryCondition delCondition = new QueryCondition();
		//生成CardSequence对象，并插入数据库
		CardSequence cardSequenceMO = new CardSequence();
		cardSequenceMO.setCardSequence(HexStringUtil.bytesToHexString(pkgVO.getCardSequence()));
		cardSequenceMO.setPhoneNumber(trans.getCellphone());
		
		delCondition.addQueryCondition("phoneNumber",inboundMsg.getPhoneNumber() , QueryExpression.EQUALS);
		cardSequenceService.deleteByCondition(delCondition);
		cardSequenceService.insert(cardSequenceMO);
		
		//生成CardPwd对象，并插入数据库
		CardPwd cardPwd = new CardPwd();
		cardPwd.setCellphone(inboundMsg.getPhoneNumber());
		cardPwd.setPassword(pkgVO.getCardPasswordDecrypt());
		cardPwd.setInitPwd(pkgVO.getCardPasswordDecrypt());
		
		delCondition = new QueryCondition();
		delCondition.addQueryCondition("cellphone",inboundMsg.getPhoneNumber() , QueryExpression.EQUALS);
		cardPwdService.deleteByCondition(delCondition);
		cardPwdService.insert(cardPwd);
		
		//调用深圳通接口
		byte[] deviceSequence = HexStringUtil.hexStringToBytes(trans.getDeviceSequence());
		byte[] sztSequence = HexStringUtil.hexStringToBytes(trans.getSztId());
		
		
		SZTRegReqTransVO sztRegReqTransVO = new SZTRegReqTransVO(deviceSequence,sztSequence,trans.getDeviceTriggerTime(),trans);
		
		
		SZTRegRequestVO regRequestVO = new SZTRegRequestVO(sztRegReqTransVO.getTransDataHexString());
		
		SZTInterface sztInterface = new SZTInterface();
		byte[] response=sztInterface.sendRequest(HexStringUtil.hexStringToBytes(regRequestVO.getMsgPackage()));
		SZTBaseResponseVO responseVO = new SZTBaseResponseVO();
		responseVO.parse(response);
		
		SZTRegResTransVO regResponseTransVO = new SZTRegResTransVO(); 
		regResponseTransVO.parse(HexStringUtil.hexStringToBytes(responseVO.getData()));
		
		
		//更新RegTrans对象
		if (regResponseTransVO.getTransResult()==0x00){//Success
			trans.setResult(AppConstant._transResult_success_szt);
			trans.setSztId(HexStringUtil.bytesToHexString(regResponseTransVO.getSztSequence()));
			trans.setOuterAuthCode(HexStringUtil.bytesToHexString(regResponseTransVO.getOuterAuthCode()));
			trans.setSztTriggerTime(regResponseTransVO.getTransDate());
			regTransService.updateById(trans);
		}else{//Failure
			System.out.println("SZT RegResponse ERROR CODE="+HexStringUtil.byteToHexString(regResponseTransVO.getTransResult()));
		}
		
		//Build UTK Reg Response Pkg
		UTKRegResponseDownlinkVO regResponseDownlinkVO = 
			new UTKRegResponseDownlinkVO(
					pkgVO.getCardSequence(),pkgSequenceService.getNextSequence(trans.getCellphone()),
					HexStringUtil.hexStringToBytes(trans.getCardAppSequence()),
					HexStringUtil.hexStringToBytes(trans.getRegSequence()),
					HexStringUtil.hexStringToBytes(trans.getOuterAuthCode()),
					HexStringUtil.hexStringToBytes(trans.getCardEffectTime()),
					HexStringUtil.hexStringToBytes(trans.getCardExpireTime()));
		byte[] responsePkg=regResponseDownlinkVO.buildPkg();
		
		
		
		//Insert outboundMsg List
		OutboundMsg outboundMsg = new OutboundMsg();
		outboundMsg.setContent(HexStringUtil.bytesToHexString(responsePkg));
		outboundMsg.setDest(0);
		outboundMsg.setPhoneNumber(trans.getCellphone());
		outboundMsg.setSendDate(System.currentTimeMillis());
		outboundMsg.setTransId(trans.getId());
		outboundMsg.setNeedRetry(1);
		outboundMsg.setMsgType(AppConstant._outbound_msg_type_regResponse);
		outboundMsgService.insert(outboundMsg);
		
	}

}
